<template>
	<div class="">
		<u-navbar bgColor="#fff" leftIconColor="#333" title="" placeholder autoBack rightIcon="download"
			@rightClick="downloadImgInUni(videoData)">
		</u-navbar>

		<video v-if="show" class="video-box" :src="videoData" id="videoEle" controls autoplay></video>

	</div>
</template>

<script lang="ts" setup>
	import { Toast, TOAST_TYPE } from "../common/Toast/index";
	import { ref } from "../../adapter-vue";
	import { TUIGlobal } from "@tencentcloud/universal-api";
	import { onLoad, onReady } from "@dcloudio/uni-app";
	const props = defineProps({
		data: {
			type: String,
			default: () => "",
		},
	});

	const videoData = ref();
	const show = ref(false);
	const videoContext = ref();
	onLoad((option : any) => {
		videoData.value = option && option.videoUrl;
		show.value = true;
	});

	onReady(() => {
		show.value = true;
		videoContext.value = TUIGlobal.createVideoContext("videoEle");
	});



	// H5下载视频
	// 创建一个Blob URL
	const createObjectURL = (video) => {
		return window.URL.createObjectURL(video);
	}

	// 下载并保存视频到设备
	const downloadVideo = (url) => {
		const xhr = new XMLHttpRequest();
		xhr.open('GET', url, true);
		xhr.responseType = 'blob';
		xhr.onload = function () {
			if (this.status === 200) {
				// 创建一个临时的URL指向视频Blob数据
				const blob = new Blob([this.response], { type: 'video/mp4' });
				const videoUrl = createObjectURL(blob);

				// 创建一个a标签用于下载
				const link = document.createElement('a');
				link.href = videoUrl;
				link.download = 'video.mp4';
				link.click();

				// 清除URL对象
				window.URL.revokeObjectURL(videoUrl);
			}
		};
		xhr.send();
	}

	const downloadImgInUni = (src : string) => {
		// #ifdef H5
		downloadVideo(src);
		// #endif
		// #ifndef H5
		//下载图片文件
		TUIGlobal.showLoading({
			title: "视频下载中……",
		});
		TUIGlobal.downloadFile({
			url: src,
			success: function (res : any) {
				TUIGlobal.hideLoading();
				TUIGlobal.saveVideoToPhotosAlbum({
					filePath: res.tempFilePath,
					success: () => {
						Toast({
							message: "视频已保存",
							type: TOAST_TYPE.SUCCESS,
						});
					},
				});
			},
			fail: function (error : any) {
				TUIGlobal.hideLoading();
				Toast({
					message: "视频保存失败",
					type: TOAST_TYPE.ERROR,
				});
			},
		});
		// #endif
	};
</script>
<style lang="scss" scoped>
	.video-box {
		width: 100vw;
		height: calc(100vh - var(--status-bar-height) - 44px);
	}
</style>